import subprocess
import json


def get_service_names():
    # 使用 curl 命令行获取 JSON 数据，禁用进度信息
    curl_command = [
        'curl',
        '-s',  # 禁用进度条输出
        'http://192.168.31.134:8848/nacos/v1/ns/catalog/services?hasIpCount=true&withInstances=false&pageNo=1&pageSize=10&serviceNameParam=&groupNameParam=&namespaceId=default',
        '--insecure'  # 跳过 SSL 证书验证
    ]

    # 执行 curl 命令并捕获输出
    try:
        result = subprocess.check_output(curl_command, stderr=subprocess.STDOUT, universal_newlines=True)

        # 确保获取到有效的内容，如果内容为空则提示错误
        if not result.strip():
            print("Error: Empty response from curl command.")
            return []

        # 解析 JSON 数据
        data = json.loads(result)

        # 输出解析后的 JSON 数据，调试用
        print("Parsed JSON data:")
        print(json.dumps(data, indent=4))

        # 提取 serviceList 中每个元素的 "name" 字段
        # for service in data.get('serviceList', []):
        #     print(service)
        #     return service['name']
        service_names = [service['name'] for service in data.get('serviceList', [])]
        return service_names
    except subprocess.CalledProcessError as e:
        print(f"Error executing curl command: {e}")
        return []
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")
        return []


def get_service_instances(service_name):
    # 构造 curl 命令，获取指定服务的实例信息
    curl_command = [
        'curl',
        '-s',
        f'http://192.168.31.134:8848/nacos/v1/ns/catalog/instances?&serviceName={service_name}&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=default',
        '--insecure'  # 跳过 SSL 证书验证
    ]

    try:
        # 执行 curl 命令并获取输出
        result = subprocess.check_output(curl_command, stderr=subprocess.STDOUT, universal_newlines=True)

        # 解析 JSON 数据
        data = json.loads(result)

        # 提取 "list" 中的每个实例的 "ip" 和 "port"
        instances = []
        for instance in data.get('list', []):
            ip = instance.get('ip')
            port = instance.get('port')
            if ip is not None and port is not None:
                instances.append({'ip': ip, 'port': port})
                # if str(ip) == "192.168.31.134" and str(port) == "8082":
                if  str(port) == "8085" or str(port) == "8083" or str(port) == "8082":
                    print("找到对应IP和端口：", ip," ", port)
                    update_instance(ip, port, service_name)
                else:
                    print("跳过", ip," ", port)

        return instances
    except subprocess.CalledProcessError as e:
        print(f"Error executing curl command for service {service_name}: {e}")
        return []
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON for service {service_name}: {e}")
        return []


# def get_service_names():
#     # 这里假设你已经从之前的请求中获取到了 service_names 列表
#     service_names = [
#         'go-demo-service',  # 示例服务名
#         'another-service'  # 假设有多个服务
#     ]
#
#     return service_names


def get_all_service_instances():
    service_names = get_service_names()

    # 用来保存所有服务的实例信息
    all_instances = []

    # 循环获取每个服务的实例信息
    for service_name in service_names:
        print(f"Fetching instances for service: {service_name}")
        instances = get_service_instances(service_name)
        if instances:
            all_instances.extend(instances)  # 将实例信息添加到列表中

    return all_instances


def update_instance(ip, port, service_name):
    # 构造 PUT 请求的 curl 命令
    curl_command = [
        'curl',

        f'http://192.168.31.134:8848/nacos/v1/ns/instance?',
        '-s',
        '-X', 'PUT',
        '--data-raw',
        f'serviceName={service_name}&clusterName=DEFAULT&groupName=DEFAULT_GROUP&ip={ip}&port={port}&ephemeral=true&weight=1&enabled=false&metadata={{}}&namespaceId=default',
        '--insecure'  # 跳过 SSL 证书验证
    ]

    try:
        # 执行 curl 命令并获取返回结果
        result = subprocess.check_output(curl_command, stderr=subprocess.STDOUT, universal_newlines=True)
        print(f"Successfully updated instance: IP={ip}, Port={port}, Response: {result}")
    except subprocess.CalledProcessError as e:
        print(f"Error executing PUT command for IP={ip}, Port={port}: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == '__main__':
    instances = get_all_service_instances()

    # 打印所有获取到的实例信息
    # print("All Instances (IP and Port):")
    # for instance in instances:
    #     ip = instance['ip']
    #     port = instance['port']
        # 执行 PUT 请求，更新实例
        # update_instance(ip, port, service_name='go-demo-service')
    